<template>
  <a-card class="general-card" title="OSS资源" :bordered="false">
    <PickSearchColumn  :rowSpan="isNormal ? 0 : 12" :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}" ></PickSearchColumn>
    <a-row class="oss-manage">
      <a-col :span="4">
        <div class="file-list">
          <a-tree :data="treeData" @select="treeSelect">
            <template #switcher-icon="node, { isLeaf }">
              <template v-if="node.key === '0'"><IconDriveFile /></template>
              <IconDown v-if="!isLeaf" />
            </template>
            <template #extra="nodeData">
              <a-dropdown @select="onIconClick($event, nodeData)" v-if="nodeData.key !== '0'">
                <icon-more style="position: absolute; right: 16px; font-size: 22px; top: 5px; color: #999999;"/>
                <template #content>
                  <a-doption value="edit">编辑</a-doption>
                  <a-doption value="delete">删除</a-doption>
                </template>
              </a-dropdown>
              <!--<IconPlus style="position: absolute; right: 8px; font-size: 12px; top: 10px; color: #3370ff;" @click="() => onIconClick(nodeData)"/>-->
            </template>
          </a-tree>
          <div class="btnBox">
            <a-button long @click="handleClickAddGroup('ADD')">添加分组</a-button>
          </div>
        </div>
      </a-col>
      <a-col :span="20">
        <div class="pic-list">
          <div class="search-box">
            <a-dropdown :popup-max-height="false">
              <a-button>更多操作 <icon-down /></a-button>
              <template #content>
                <a-doption @click="() => init(apiParams, 'refresh')">刷新</a-doption>
                <a-doption @click="removeAll">批量删除</a-doption>
              </template>
            </a-dropdown>
            <!--<uploadPicInput :tablePageRef="tablePageRef" :dataList="{directoryPath: apiParams.fileDirectoryId}" />-->
            <uploadPicInput :data-list="{ directoryPath: apiParams.fileDirectoryId }" style="margin-left: 20px" @onSuccess="() => init()"/>
          </div>
          <a-checkbox-group
              v-model="selectedOss"
              :default-value="selectedOss"
              @change="selectOssChange"
          >
            <div class="img-box">
              <div
                  v-for="(item, index) in ossFileList"
                  :key="index"
                  class="img-item"
              >
                <a-checkbox :value="item.id">
                  <template #checkbox="{ checked }">
                    <div
                        class="card"
                        :class="{ 'custom-checkbox-card-checked': checked }"
                        @mouseover="mouseOver(item)"
                        @mouseleave="mouseLeave(item)"
                    >
                      <div className="custom-checkbox-card-mask"
                      ><div className="custom-checkbox-card-mask-dot"
                      /></div>
                      <img :src="item.url" alt="" />
                      <!--<a-image :src="item.url" alt="无效的图片链接"></a-image>-->
                      <div v-if="item.isShowPreview" class="preview">
                        <div @click.prevent="previewEditClick($event, item)"
                        ><a-tooltip content="下载"
                        ><icon-cloud-download size="16" /></a-tooltip
                        ></div>
                        <div @click.prevent="previewDeleteClick($event, item)"
                        ><a-tooltip content="删除"
                        ><icon-delete size="16" /></a-tooltip
                        ></div>
                        <div @click.prevent="previewEyeClick($event, item)"
                        ><a-tooltip content="预览"
                        ><icon-eye size="16" /></a-tooltip
                        ></div>
                      </div>
                    </div>
                  </template>
                </a-checkbox>
                <div class="text">
                  <a-tooltip :content="item.name"
                  ><div>{{ item.name }}</div></a-tooltip
                  >
                </div>
              </div>
            </div>
          </a-checkbox-group>
          <div class="pagination-box">
            <a-pagination
                :current="apiParams.current"
                :total="apiParams.total"
                :page-size="apiParams.pageSize"
                @change="paginationChange"
            />
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 编辑文件名 -->
    <a-modal :width="550" v-model:visible="modalVisible">
      <template #title> 编辑文件名 </template>
      <a-form ref="formRef" :model="form">
        <a-form-item field="name" label="原文件名" :rules="[REQUIRED]">
          <a-input v-model="form.name"></a-input>
        </a-form-item>
        <a-form-item field="fileKey" label="存储文件名" :rules="[REQUIRED]">
          <a-input v-model="form.fileKey" disabled></a-input>
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="text-align: right">
          <a-button style="margin-right: 5px" @click="modalVisible = false">取消</a-button>
          <a-button type="primary"  @click="handleSubmit">提交</a-button>
        </div>
      </template>
    </a-modal>
    <!-- 添加/编辑分组模态框 -->
    <a-modal :width="500" v-model:visible="enableGroupVisible">
      <template #title>{{groupFormType==='ADD'?'添加分组':'编辑分组'}}</template>
      <a-form ref="groupFormRef" :model="groupForm">
        <a-form-item field="id" label="所在分组" :rules="[REQUIRED]">
          <a-tree-select :data="treeData" :label-in-value="true" :default-value="defaultValue" v-model:model-value="defaultValue"
                          placeholder="Please select ..." @change="treeSelectChange" tree-checked-strategy="all"></a-tree-select>
        </a-form-item>
        <a-form-item field="directoryName" label="分组名称" :rules="[REQUIRED]">
          <a-input v-model="groupForm.directoryName"></a-input>
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="text-align: right;">
          <a-button style="margin-right: 5px" @click="enableGroupVisible = false">取消</a-button>
          <a-button type="primary" @click="groupFormSubmit">提交</a-button>
        </div>
      </template>
    </a-modal>
    <!-- 预览图片 -->
    <a-modal v-model:visible="picVisible" title="查看图片" draggable>
      <a-image :src="file.url" width="100%" alt="无效的图片链接"></a-image>
      <template #footer>
        <span>文件类型：{{ file.fileType }} 文件大小：{{ file.msize }}</span>
      </template>
    </a-modal>
</a-card>
</template>

<script setup lang="ts">
import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';

import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';
import { getFileListData } from '@/api/setting';
import { ref, watch, reactive, onMounted, h } from 'vue';
import { useRouter } from 'vue-router';
import uploadPicInput from '@/components/upload-pic/index.vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { REQUIRED } from '@/utils/validator';
import { deleteFile, renameFile, getFileDirectory, addFileDirectory, updateFileDirectory, delFileDirectory } from '@/api/index';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { IconDriveFile, IconDown, IconStar, IconUp } from '@arco-design/web-vue/es/icon';

const treeData = ref<Array<any>>([]); // 树结构
const enableGroupVisible = ref<boolean>(false); // 添加/编辑分组模态框
const groupFormType = ref('ADD');
const groupForm = ref<any>({
  id: '0',
  directoryName: '',
});
const groupFormRef = ref();
// const defaultValue  = ref({ value: '0', label: '全部分类' });
const defaultValue  = ref('0');
const insertOrUpdate = ref('insert'); // insert：添加分组，update：修改分组
// 组件模式
const props = defineProps({
  templateModel: {
    type: String,
    default: 'normal',
  },
  closeModel: {
    type: null
  }
})
const isNormal: boolean = props.templateModel === 'normal';
//  获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
const formRef = ref<FormInstance>();
const tablePageRef = ref('');

const modalVisible = ref<boolean>(false) // 弹框是否显示
const selectCount = ref<number>(0) // 多选计数
const selectList = ref([]) // 多选数据
const totalSize = ref<string>('') // 文件大小统计
const form = ref({ // 表单
  name: '',
  fileKey: '',
  id: '',
  oldKey: '',
})
// 传递的参数
const apiParams = ref<any>({
  // 搜索框对应data对象
  fileType: "",
  pageSize: 27, // 页面大小
  sort: "createTime", // 默认排序字段
  order: "desc", // 默认排序方式
  // startDate: "", // 起始时间
  // endDate: "", // 终止时间
  startTime: '',
  endTime: '',
  title: '',
  total: 0,
  current: 1,
  fileDirectoryId: ''
})
const thumbnailParameter = JSON.parse(JSON.stringify({ ...apiParams.value, pageSize: 15 }))
const oldKey = ref<string>('') // 请求参数
const fileType = ref<string>('all') // 文件类型
const thumbnailList = ref([])
const emit = defineEmits<{
  (e: 'changOssImage', url: string): void;
  (e: 'selected', val: any, type: string): void;
}>() as any;

const selectedOss = ref<Array<any>>([]);
const selectedKey = ref(['0']);
const ossFileList = ref<Array<any>>([]);
const picVisible = ref(false); // 图片的modal
const file = ref<any>({}); // 文件数据
const columnsSearch: Array<SearchRule> = [
  {
    label: '图片名称',
    model: 'name',
    disabled: false,
    input: true,
  },
];
// oss资源请求接口
const init = async (params = apiParams.value, type = '') => {
  const res = await getFileListData(params);
  if (res.data.success) {
    res.data.result.records.forEach((item: any) => {
      item.selected = false;
    });
    ossFileList.value = res.data.result.records.map((item: any) => {
      item.isShowPreview = false;
      return item;
    });
    const { current, size, total } = res.data.result;
    apiParams.value.current = current;
    apiParams.value.pageSize = size;
    apiParams.value.total = total;
    if (type === 'refresh') {
      Message.success('刷新成功！');
    }
  }
};
// 分页改变
const paginationChange = (v: any) => {
  apiParams.value = { ...apiParams.value, pageNumber: v };
};
// 复选框值改变时触发
const selectOssChange = (value: any) => {
  emit('selected', selectedOss.value);
};
const mouseOver = (item: any) => {
  item.isShowPreview = true;
};
const mouseLeave = (item: any) => {
  item.isShowPreview = false;
};
// 编辑图片名称
const previewEditClick = (event: any, v: any) => {
  event.stopPropagation();
  window.open(
      `${v.url}?attname=&response-content-type=application/octet-stream`
  );
};
// 删除图片
const previewDeleteClick = (event: any, v: any) => {
  event.stopPropagation();
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除文件${v.name}?`,
    alignCenter: false,
    onOk: async () => {
      const res = await deleteFile(v.id);
      if (res.data.success) {
        Message.success(`删除文件${v.name}成功`);
        init();
      }
    },
  });
};
// 预览图片
const previewEyeClick = (event: any, v: any) => {
  event.stopPropagation();
  file.value = v;
  file.value.msize = `${((v.fileSize * 1.0) / (1024 * 1024)).toFixed(2)}MB`;
  picVisible.value = true;
};


// 提交
const handleSubmit = async () => {
  const params = {
    id: form.value.id,
    key: oldKey.value,
    newKey: form.value.fileKey,
    newName: form.value.name
  }
  const auth = await formRef.value?.validate();
  if (!auth) {
    const res = await renameFile(params)
    if (res.data.success) {
      Message.success('操作成功');
      modalVisible.value = false
      // tablePageRef.value.init();
    }
  }
}
// 批量删除文件
const removeAll = () => {
  if (selectedOss.value.length <= 0) {
    Message.warning('您还未选择要删除的数据');
    return
  }
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除所选的${selectedOss.value.length}个文件?`,
    alignCenter: false,
    onOk: async () => {
      let ids = "";
      selectedOss.value.forEach((e: any) => {
        ids += `${e},`
      })
      ids = ids.substring(0, ids.length - 1);
      const res = await deleteFile(ids);
      if (res.data.success) {
        Message.success('批量删除文件成功');
        // tablePageRef.value.init();
        init();
      }
    },
  });
}
// 文件目录格分类式化方法
const getTree = (tree = []) => {
  const arr =[] as any;
  if (!!tree && tree.length !== 0) {
  // :field-names="{ children: 'children', title: 'directoryName', key: 'id' }"
    tree.forEach((item: any) => {
      const obj = {} as any;
      obj.title = item.directoryName;
      obj.key = item.id; // 拥有者id
      obj.type = item.directoryType; // 用户类型
      obj.label = item.directoryName;
      obj.level = item.level;
      obj.expand = false;
      obj.selected = false;
      obj.contextmenu = true;
      obj.parentId = item.parentId;
      obj.children = getTree(item.children);
      obj.icon = () => h(IconDriveFile);
      arr.push(obj);
    })
  }
  return arr;
};
// 获取文件目录列表
const getAllList = () => {
  getFileDirectory().then(res => {
    if (res.data.success) {
      treeData.value = getTree(res.data.result);
      treeData.value.unshift({
        title: '全部分类',
        label: '全部分类',
        value: '0',
        level: 0,
        children: [],
        id: '0',
        categoryId: 0,
        key: '0',
        // icon: () => h(IconDriveFile)
      });
    }
  })
};
// 添加/修改目录
const handleClickAddGroup = (type: any) => {
  enableGroupVisible.value = true;
  groupFormType.value = type;
  if (type === 'ADD') {
    groupForm.value = {id: '0', directoryName: '', parentId: '0'};
    defaultValue.value = '0';
  }
};
// 添加/修改分组模态框
const treeSelectChange = (val: any) => {
  groupForm.value.parentId = val.value;
};
// 添加/修改分组提交
const groupFormSubmit =  async () => {
  const auth = await groupFormRef.value?.validate();
  if (!auth) {
    const params = {...groupForm.value};
    params.level = params.parentId == '0' ? 0 : 1;
    let res;
    if (groupFormType.value === 'ADD') {
      // 添加
      delete params.id;
      res = await addFileDirectory(params);
    } else {
      // 修改
      res = await updateFileDirectory(params);
    }
    if (res.data.success) {
      enableGroupVisible.value = false;
      getAllList();
    }
  }
};
// 删除分组
const groupFormDelete = (key: any) => {
  modal.confirm({
    title: '确认删除',
    content: `是否删除该分组？`,
    alignCenter: false,
    onOk: async () => {
      delFileDirectory(key).then(res => {
        if (res.data.success) {
          Message.success('删除成功！');
          getAllList();
        }
      })
    }
  })
}
// 操作文件目录列表
const onIconClick = (event: any, nodeData: any) => {
  if (event === 'edit') {
    handleClickAddGroup('EDIT');
    groupForm.value.directoryName = nodeData.label;
    groupForm.value.id = nodeData.key;
    groupForm.value.level = nodeData.level;
    groupForm.value.parentId = nodeData.parentId;
    // defaultValue.value = { value: nodeData.key, label: nodeData.label };
    defaultValue.value = nodeData.parentId;
  }
  if (event === 'delete') {
    groupFormDelete(nodeData.key);
  }
};
// 选择目录回调
const treeSelect = (selectedKeys: any, data: any) => {
  let id = selectedKeys[selectedKeys.length-1];
  if (id == '0') {
    delete apiParams.value.fileDirectoryId;
  } else {
    apiParams.value.fileDirectoryId = id;
  }
};

onMounted(() => {
   if (!isNormal) {}
  getAllList();
  init();
})
// 初始化监听
watch(
    () => [apiParams.value],
    (val) => {
      init();
    },
    { deep: true }
);
</script>
<style lang="less" scoped>
@import "./ossManage.less";
  :deep(.arco-tree-node-title) {
    width: 100%;
  }
</style>


